const { USER_LIST_SORT_SET } = require('../consts/system')

const { Success, SysErr } = require('../response/code')

const client = require('../util/redis')

const { TOKEN_PREFIX } = require('../consts/system')

class SysUserOnlineService {
  async del(ctx) {
    try {
      const body = ctx.request.body
      const conn = await client.connect()
      const result = await conn.zRem(USER_LIST_SORT_SET, body.phone)
      const remove = await conn.del(`${TOKEN_PREFIX}:${body.phone}`)
      await conn.close()

      ctx.body = new Success(result == 1 && remove == 1).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }

  async list(ctx) {
    try {
      const query = ctx.request.query
      const offset = (query.pageNo - 1) * query.pageSize

      const conn = await client.connect()
      const data = await conn.zRange(USER_LIST_SORT_SET, offset, query.pageSize)
      const total = await conn.zCount(USER_LIST_SORT_SET, '-inf', '+inf')

      await conn.close()

      const result = {
        list: data,
        count: total,
      }
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }
}

module.exports = new SysUserOnlineService()
